package kr.hkit.powerjava.chapter25.chat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class QuizServer {
	public static void main(String[] args) throws IOException {
		ServerSocket serverSocket = null;
		
		PrintWriter out = null;
		BufferedReader in = null;
		
			
		try {
			serverSocket = new ServerSocket(5555);
			
		} catch (IOException e) {
			System.err.println("다음의 포트 번호에 연결할 수 없습니다.: 5555");
			System.exit(-1); //비정상종료
		}
		
		

		Socket clientSocket = null;
		
		
		try {
			clientSocket = serverSocket.accept();
			
		} catch (IOException e) {
			System.err.println("accept() fail");
			System.exit(-1);
		}
		
		out = new PrintWriter(clientSocket.getOutputStream(), true);
		in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
		
		String inputLine;
		String outputLine;
		
		QuizProtocol qp = new QuizProtocol(); //서버쪽에서...
		
		outputLine = qp.process(null); //"퀴즈를 시작 하겠습니다 뜸" 
		out.println(outputLine); //클라이언트에게 시작을 전송
		
		while((inputLine = in.readLine()) != null) { //클라이언트에서 보낸것을 받는것. 처음엔 y또는 n
			outputLine = qp.process(inputLine);
			out.println(outputLine); //확인차 맞는지 클라이언트에게 보냄
			if(outputLine.equalsIgnoreCase("quit")) {
				break;
			}
		}
		in.close();
		out.close(); 
		clientSocket.close();
		serverSocket.close(); //순서대로 소켓도 클로즈해줘야함!!!!!
		
	}
}
